<?php
/**
 * Created by PhpStorm.
 * User: 15272
 * Date: 2018/12/28
 * Time: 20:27
 */

/**
 *创建人：李国铃
 *电话、微信:15372566896
 *Q   Q：1277613171
 */

namespace app\admin\controller;


use app\admin\model\CodePasswordModel;
use app\admin\model\GoodsModel;
use app\admin\model\UserModel;
use app\admin\validate\AddKPValidate;
use app\admin\validate\DaoChuValidate;
use app\admin\validate\GoodsValidate;
use app\admin\validate\UpdateSortValidate;
use cmf\controller\AdminBaseController;
use think\Db;

class GoodsController extends AdminBaseController
{
    //产品列表
    public function index()
    {

        $this->view->data = $data = GoodsModel::whereNull('delete_time')
            ->where(function ($req) {
                if ($type = input('type')) {
                    return $req->where('parent_id', $type);
                }
            })

            ->order('sort', 'desc')
            ->paginate(20, false, [
                'query' => ['type' => input('type')]
            ]);

        return $this->fetch();
    }

    //添加产品
    public function addGoods()
    {
        if (request()->isAjax()) {

            $validate = new GoodsValidate();

            if (!$validate->check($_POST)) {
                $this->error($validate->getError());
            }
            $goods = new GoodsModel();
            if ($g_id = input('g_id/n')) {
                //修改
                $stte = $goods->allowField(true)->save($_POST, ['g_id' => $g_id]);
            }
            else {
                $_POST['create_time'] = time();
                //添加
                $stte = $goods->allowField(true)->save($_POST);
            }

            if ($stte) {
                $this->success('保存成功');
            }
            else {
                $this->error('保存失败');
            }
        }

        if ($id = input('id/n')) {
            //获取编辑的信息
            $data = GoodsModel::where('g_id', $id)->find();
            if (!$data) {
                $this->success('产品不存在');
            }
            $this->assign('data', $data);
        }

        return $this->fetch();
    }

    //删除产品
    public function delGoods()
    {
        $id = input('id/n');
        //删除下面的卡密
        CodePasswordModel::where('goods_id', $id)->whereNull('chown')->delete();
        //删除产品
        $data = GoodsModel::where('g_id', $id)->find();
        $data = $data->save(['delete_time' => time()]);
        if ($data) {
            return $this->success('删除成功');
        }
        else {
            return $this->error('删除失败');
        }

    }

    //查看卡密
    public function lockKP()
    {
        $this->view->g_id = $g_id = input('goods_id/n');

        $this->view->data = $data = CodePasswordModel::where(function ($req) use ($g_id) {
            if ($g_id) {
                return $req->where('goods_id', $g_id);
            }
        })->order('create_time', 'desc')->paginate(20, false, [
            'query' => ['goods_id' => input('goods_id/n')]
        ])->each(function ($row) {
            $row['state_name'] = codeState($row);
            return $row;
        });


        //获取产品
        $this->view->goodsAll = GoodsModel::whereNull('delete_time')->select();
        return $this->fetch();
    }

    //添加卡密
    public function addKP()
    {

        if (request()->isAjax()) {
            $addV = new AddKPValidate();
            if (!$addV->check($_POST)) {
                $this->error($addV->getError());
            }

            //分析卡密
            $KP = input('post.content') . "\n";
            preg_match_all("/.*?\n/s", $KP, $result);
            $KPArray = array_unique($result[0]);

            $insertArray = array();
            $thisTime = time();
            foreach ($KPArray as $item) {
                $item = trim($item);
                if (!empty($item)) {
                    $insertArray[] = [
//                        'card_number'=>ranOrder()
                        'content' => $item
                        , 'create_time' => $thisTime
                        , 'goods_id' => input('g_id')
                    ];
                }

            }

            $code = new CodePasswordModel();
            $state = $code->saveAll($insertArray);
            if ($state) {
                $this->success('添加成功，共' . count($insertArray) . '行');
            }
            else {
                return $this->error('添加失败');
            }

        }
        $this->assign('g_id', input('g_id/m'));
        $this->view->goodsAll = $goods = GoodsModel::whereNull('delete_time')->select();

        return $this->fetch();
    }

    //删除卡密
    public function delKP()
    {
        $id = input('code_id');
        $code_data = CodePasswordModel::where('card_number', $id)->find();

        if ($code_data['chown'] != null) {
            $this->error('待支付或已支付的卡密不能删除');
        }
        $state = $code_data->delete();

        if ($state) $this->success('删除成功');
        else $this->error('删除失败');
    }

    //会员通过
    public function setPass()
    {
        $user = UserModel::where('id', input('user_id/n'))->find();
        $state = $user->save([
            'admin_audit' => 1
        ]);
        if ($state) return $this->success('审核成功');
        else return $this->error('审核失败');

    }

    //查看卡密内容
    public function code_password_info()
    {
        $where = [];
        //匹配卡号
        if ($val = input('code_id/n')) {
            $where['code.card_number'] = $val;
            $this->assign('code_id', $val);
        }

        //匹配订单号
        if ($val = input('order_number')) {
            $where['order.order_number'] = $val;
            $this->assign('order_number', $val);
        }

        //查询数据
        $this->view->data = $data = Db::name('code_password')->alias('code')
            ->join($this->_db_prefix . 'order order', 'code.order_id = order.order_id')
            ->where($where)
            ->order('code.card_number', 'DESC')
            ->paginate(20, false, [
                'query' => [
                    'code_id' => input('code_id/n')
                    , 'order_number' => input('order_number/n')
                ]
            ]);
        return $this->fetch();
    }

    //导出卡密
    public function derive()
    {

        if (request()->isAjax()) {

            //验证参数
            $va = new DaoChuValidate();

            if (!$va->check($_POST)) {
                $this->error($va->getError());
            }

            $goods = GoodsModel::get(input('id/n'));
            if (!$goods) $this->error('产品不存在');

            //是否出售的
            $chu_shou = input('chu_shou/n');
            if(!in_array($chu_shou,[1,2])) $this->error('出售类型错误');

            $data = CodePasswordModel::where([
                'goods_id' => $goods['g_id'],/*对应的产品*/
//                'pay_state' => ['<>', 1],
                'create_time' => ['between',
                    [
                        strtotime(input('time/s')),
                        strtotime(input('end_time/s'))
                    ]
                ],

            ])
                ->order('card_number asc')
                ->where(function ($req) {
                    return $req->where(['next_order_time' => ['<', time() - $this->_bay_time]])
                        ->whereOr('next_order_time', 'null');
                })
                ->where(function ($req) use ($chu_shou){

                    if($chu_shou == 1){
                        //未出售的
                        return $req->where('pay_state','<>',1);
                    }else{
                        //已出售
                        return $req->where('pay_state','=',1);
                    }
                })
                ->select();

            $del_id = [];
            $name = date('YmdHis') . '.txt';
            $txt = '';
            foreach ($data as $key) {
                $del_id[] = $key['card_number'];
                $txt .= $key['content'] . "\r\n";
            }

            //空验证
            if (empty($txt)) $this->error('没有卡密可以导出');

            file_put_contents($name, $txt);

            //检测是否删除
            if (input('delete/n') == 2) {
                //删除卡密
                Db::name('code_password')->whereIn('card_number', implode(',', $del_id))->delete();
            }

            $this->success('导出成功', '', [
                'name' => $name,
                'href' => 'http://' . $_SERVER['HTTP_HOST'] . '/' . $name
            ]);
        }

        return $this->fetch();
    }
    
    //修改排序
    public function update_sort()
    {
        $sort = new UpdateSortValidate();
        if(!$sort->check($_POST)){
            return $this->error($sort->getError());
        }

        $goods = GoodsModel::get(input('id'));
        $goods->sort = input('sort_val');

        if($goods->save()){
            return $this->success(lang('编辑成功'));
        }else{
            return $this->error(lang('编辑失败'));
        }
    }

}